// pages/blank/blank.js
let app = getApp()
import {
  request,
  requestHasToken
} from '../../service/network'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    url: '',
    login: false,
    phone: true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let url = this.data.url
    //判断是否有数据
    if (JSON.stringify(options) != '{}') {
      url = ''
      for (var key in options) {
        if(key=='url') {
          url += options[key]+'?'
        }
      }
      for (var key in options) {
        if(key!='url') {
          url += key + '=' + options[key]+'&'
        }
      }
      url=url.substr(0,url.length-1)
    }
    this.setData({
      url
    })
    console.log(options,this.data.url);

    if(wx.getStorageSync('phone') && wx.getStorageSync('phone')!='') {
      this.setData({
        phone: true
      })
    }
    
    /* wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          app.globalData.authority = true;
          wx.getUserInfo({
            success: (res3) => {
              wx.setStorageSync('userInfo', res3.userInfo); //存储userInfo
              this.doLogin()
            }
          });
        }
      }
    }) */
  },
  handleUserinfo(e) {
    wx.setStorageSync('userInfo', e.detail.userInfo); //存储userInfo
    this.setData({
      login: true,
    })
    if(wx.getStorageSync('phone') ==null  || wx.getStorageSync('phone').trim()=='') {
      this.setData({
        phone: false
      })
    }
    this.doLogin()
  },
  //https://blog.csdn.net/qq_39471272/article/details/87272170
  getPhoneNumber: function (e) {
    if(e.detail.errMsg=='getPhoneNumber:ok'){
      wx.login({
        success: res => {
          wx.request({
            url: App.config.baseApi + 'api/nt/xcx/wxOauth',
            data: {
              'encryptedData': e.detail.encryptedData,
              'iv': e.detail.iv,
              'codes': res.code
            },
            header: {
              'content-type': 'application/json'
            },
            method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
            success:  (res) =>{
              // console.log('phone',res,res.data.phoneNumber );
              
              wx.setStorageSync('phone', res.data.phoneNumber);
              this.setData({
                phone: true
              })
              this.doLogin()
              /* wx.showToast({
                title: "号码为："+res.data.phoneNumber,
                icon: 'none'
              }) */
            },
            fail: function (err) {
              console.log(err);
            }
          })
        }
      })
    }
  },
  cancle() {
    wx.redirectTo({
      url: this.data.url
    })
    /* wx.navigateBack({
      delta: 1
    }) */
  },

  doLogin() {
    if(this.data.phone&& this.data.login) {
      const token = wx.getStorageSync('token')
      if (token && token.length !== 0) {
        this.check_token(token)
      } else { //没有token进入登录操作
        this.login()
      }
    }
  },
  check_token(token) {
    wx.request({
      url: App.config.baseApi + 'api/xcx/auth',
      method: 'post',
      data: {},
      header: {
        Authorization: 'Bearer ' + wx.getStorageSync('token'),
        'content-type': 'application/x-www-form-urlencoded;charset=utf-8' // 默认值
      },
      dataType: 'json',
      success: (res) => {
        if (res.data.code == 0) {
          this.navigate_go_dutch()
        } else {
          this.login()
        }
      },
    })
  },
  login() {
    wx.login({
      success: (res) => {
        // 1.获取code
        // code只有5分钟的有效期
        const code = res.code
        // 2.将code发送给我们的服务器
        request({
          url: 'api/nt/xcx/login',
          data: {
            code,
            ...wx.getStorageSync('userInfo'),
            sex: wx.getStorageSync('userInfo').gender,
            avatar: wx.getStorageSync('userInfo').avatarUrl,
            phone: wx.getStorageSync('phone')
          }
        }).then((loginres) => {

          const logindata = loginres.data
          if (logindata.code == 0) {
            wx.setStorageSync('token', logindata.access_token)
            this.navigate_go_dutch()
          }
        })
      },
    })
  },
  navigate_go_dutch() {
    wx.showToast({
      title: '登录成功!',
      icon: 'success',
      duration: 1500
    })
    wx.redirectTo({
      url: this.data.url
    })
  }
})